/*
 * @Author: 丁平|1572804782@qq.com(dingping)
 * @Date: 2022-02-12
 * @LastEditors: 周润玉|zhourunyu1@outlook.com(zhourunyu)
 * @LastEditTime: 2022-07-13 17:43:29
 * @Description: 
 * @Administrator: 丁平|1572804782@qq.com(dingping)
 * @Copyright: 1.0.3
 */

import WorkReportMainApi from '../../../../../../public/js/common/api/mybusiness/workreport/workreportmain.api.js'
import { ReportEnumToString } from '../../../../../../public/js/common/enum/report.enum.js';
import doT from '../../../../../../public/vendor/template/doT.js';
import EmployeeMgtApi from '../../../../../../public/js/common/api/hr/hr.api.js';
import WxcodeApi from '../../../../../../public/js/common/api/account/wxcode.api.js';
import watermark from '../../../../../../public/js/common/watermark.js';

const _reportTemplate = doT.template($('#report-contents-item-template').text());
const _isNothing = `<div class="weui-loadmore weui-loadmore_line">
<span class="weui-loadmore__tips">暂无数据</span>
</div>`;
const _picker = `<div class="toolbar">
<div class="toolbar-inner">
<a href="javascript:;" class="picker-button close-picker" style="color:#427ce7;margin-right:1.125rem;display:flex;align-items:center">{{closeText}}</a>
<h1 class="title" >{{title}}</h1>
</div>
</div>`;
const toolbarTemplateMe = `<div class="toolbar">
<div class="toolbar-inner">
<a href="javascript:;" class="picker-button reset-picker" style="color:#427ce7;font-size:20px;margin-right:80px;display:inline-block;line-height:100%">重置</a>
<a href="javascript:;" class="picker-button close-picker" style="color:#427ce7;font-size:20px;margin-right:18px;display:inline-block;line-height:100%">{{closeText}}</a>
<div class="weui-flex dtPicker-container" style="text-align:left">
<a class="weui-flex__item dtPicker-hightLight-Cotainer" style="border-radius: 5px 0 0 5px;">
  <span class="startDate chooseDate" id="startDateRe">开始时间</span>
</a>
<a class="weui-flex__item dtPicker-normal-Cotainer" style="border-radius: 0 5px 5px 0;">
  <span class="endDate chooseDate" id="endDateRe">结束时间</span>
</a>
</div>
</div>
</div>`;
const toolbarTemplate = `<div class="toolbar" id="me-date-screening">
<div class="toolbar-inner">
<a href="javascript:;" class="picker-button reset-pickerMe" style="color:#427ce7;font-size:20px;margin-right:80px;display:inline-block;line-height:100%">重置</a>
<a href="javascript:;" class="picker-button close-picker" style="color:#427ce7;font-size:20px;margin-right:18px;display:inline-block;line-height:100%">{{closeText}}</a>
<div class="weui-flex dtPicker-container" style="text-align:left">
<a class="weui-flex__item dtPicker-hightLight-Cotainer" style="border-radius: 5px 0 0 5px;">
  <span class="startDate chooseDate" id="startDateMe">开始时间</span>
</a>
<a class="weui-flex__item dtPicker-normal-Cotainer" style="border-radius: 0 5px 5px 0;">
  <span class="endDate chooseDate" id="endDateMe">结束时间</span>
</a>
</div>
</div>
</div>`;

const _type = {
    '所有类别': '', '日报': 1, '周报': 2, '月报': 3, '汇报': 4
}

const _page = {
    pageSize: 20,
    pageIndex: 0,
    totalPages: -1,

};
const _mePageScreening = {
    reportStartDate: "", reportEndDate: "", reportType: ""
};
/**
 * @file看工作汇报
 */
(function (window, document, $) {
    let _vm, receivePeopleList = [], leftList = [], rightList = [];

    $(function () {
        _vm = new Vue({
            el: "#look-report-page",
            data() {
                return {
                    quickQuery: '',
                    page: { ..._page },
                    mePageScreening: { ..._mePageScreening },
                    pageScreening: { ..._mePageScreening },
                    quickMeQuery: '',
                    mePage: { ..._page }
                }
            },
            methods: {
                navbarClick: function (e) {
                    $('#my-received').css({ 'display': '' });
                },
                clear: function () {
                    this.quickQuery = "";
                    _reset();
                },
                clearMe: function () {
                    this.quickMeQuery = "";
                    _resetMe();
                }
            },
        });
        if (!Utils.IsNotNull(SN.H5.WorkReportMain.Employee)) {
            WorkReportMainApi.getLoginUserToStaff().then(res => {
                SN.H5.WorkReportMain.Employee = res;
            });
        }
        // watermarkBgImg(); // 水印
        initCommand();
        initData();
        initMeData();
        templatePickerInitMe();
        datetimePickerInitMe();
        templatePickerInit();
        datetimePickerInit();
        weui.searchBar('#search_bar');
        weui.searchBar('#search_bar-me');
        weui.searchBar('#receive-searchdiv');
        let _state = Utils.GetRouterState('lookreport');
        if (Utils.IsNotNull(_state)) {
            let _json = JSON.parse(_state);
            $(`#look-report-page-navbar a[href='${_json.state}']`).trigger("click");
            setTimeout(() => {
                $(_json.state).addClass('weui-tab__bd-item--active');
            })
            window.sessionStorage.removeItem("lookreport");
        }
    });
    const watermarkBgImg = async () => {
        let _userInfo = JSON.parse(Utils.GetSessionStorage("SNLoginUserInfo")) || {};

        if (!Utils.IsNotNull(_userInfo)) {
            let _json = await WxcodeApi.queryUserName();
            Utils.SetSessionStorage("SNLoginUserInfo", _json);
            return EmployeeMgtApi.getLoginUserToStaff(Utils.GetQueryString('state') || '').then(res => {
                watermark.set((_json.curUserName || "") + res.code);// 水印
            }).catch(_ => {
                watermark.set(_json.curUserName || "");// 水印
            });
        }
        EmployeeMgtApi.getLoginUserToStaff(Utils.GetQueryString('state') || '').then(res => {
            watermark.set((_userInfo.curUserName || "") + res.code);// 水印
        }).catch(_ => {
            watermark.set(_userInfo.curUserName || "");// 水印
        });
    }

    SN.H5.WorkReportMain.LookReportList = () => {
        _reset();
        _resetMe();
    }
    SN.H5.WorkReportMain.setReceivePeopleList = (list) => {
        receivePeopleList = list;
        _vm.page = { ..._page };
        initData();
    }


    const initCommand = () => {
        $(document).on('click', '#me-received-infinite span[data-flag=table-click-edit]', function (e) {
            let id = $(this).attr('data-id');
            Utils.SetRouterState("lookreport", JSON.stringify({
                state: $('#look-report-page-navbar .weui-bar__item--on').attr('href'),
                main: $('#main-tabbar .weui-bar__item--on').attr('id')
            }));
            window.location.href = `./writereport/writereportedit.html?id=${id}&_=${new Date().getTime()}`;
        });
        //TODO : 删除工作汇报
        //Date :2022-02-15 13:46:28
        //create丁平
        $(document).on('click', '#me-received-infinite span[data-flag=table-click-delete]', function (e) {
            let id = $(this).attr('data-id');
            $.confirm({
                title: '删除提示',
                text: '确定删除当前工作汇报内容',
                onOK: function () {

                    WorkReportMainApi.deleteWkrptsBill(id).then(res => {
                        _resetMe();
                    })
                },
                onCancel: function () {
                }
            });
        });
        changeTime();

        //TODO : 分页查询我提交的工作汇报
        //Date :2022-02-15 13:45:34
        //create丁平
        $("#me-received-infinite").infinite().on("infinite", function () {
            let _data = _vm._data.mePage;
            if (_data.pageIndex == _data.totalPages) return;
            let self = this;
            if (self.loading) return;
            self.loading = true;
            setTimeout(function () {
                self.loading = false;
                initMeData();
            }, 500);   //模拟延迟
        });
        //TODO : 搜索提交的工作汇报
        //Date :2022-02-15 13:46:46
        //create丁平
        $("#search_bar-me form").submit(function () {
            _resetMe();
            return false;
        }).on("input propertychange", Utils.throttle(_resetMe, 500))

        //TODO : 人员查询搜索
        //Date :2022-02-15 11:09:37
        //create丁平
        $("#receive-searchdiv form").submit(function () {
            _mainSearch();
            return false;
        }).on("input propertychange", Utils.throttle(_mainSearch, 500));

        $('#receive-searchClear').on('click', function () {
            $('#receive-searchInput').val('');
            _mainSearch();
        })
        //TODO : 人员查询取消
        //Date :2022-02-15 11:10:08
        //create丁平
        $('#receive-searchInput-cancel').on('click', function () {
            $('#receive-searchInput').val('');
            SN.H5.WorkReportMain.ReceiveSearch.InputSearch();
        });
        $("#received-infinite").infinite().on("infinite", function () {
            let _data = _vm._data.page;
            if (_data.pageIndex == _data.totalPages) return;
            let self = this;
            if (self.loading) return;
            self.loading = true;
            setTimeout(function () {
                self.loading = false;
                initData();
            }, 500);   //模拟延迟
        });
        $("#search_bar form").submit(function () {
            _reset();
            return false;
        }).on("input propertychange", Utils.throttle(_reset, 500))

        //TODO : 所有人搜索
        $('#me-search-people').on('click', function () {
            SN.H5.WorkReportMain.ReceiveSearch.ContactPopupClick();
        });
        //TODO : 所有人选择确认
        $("#receive-subEmployees").on('click', function () {
            SN.H5.WorkReportMain.ReceiveSearch.ContactPopupConfirmClick();
        });
        //TODO : 人员搜索取消事件
        //Date :2022-02-15 10:03:34
        //create丁平
        $("#receive-subEmployees-cancel").on('click', function () {
            SN.H5.WorkReportMain.ReceiveSearch.ContactPopupCancelClick();
        });
        $(document).on('click', '#receive-iscroll .weui-check__label', function (event) { // 选中input 事件
            event.preventDefault();
            SN.H5.WorkReportMain.ReceiveSearchCheckbox(this);
        });
        $("#receive-iscroll").infinite().on("infinite", function () {

        });
        //TODO : 重置时间选择器
        //Date :2022-02-15 14:58:35
        //create张双磊
        $(document).on('click', '.reset-picker', function () {
            $('#startDateRe').text('开始时间')
            $('#endDateRe').text('结束时间')
            $('#startDateRe').attr('data-value', '')
            $('#endDateRe').attr('data-value', '')
        })
        $(document).on('click', '.reset-pickerMe', function () {
            $('#startDateMe').text('开始时间')
            $('#endDateMe').text('结束时间')
            $('#startDateMe').attr('data-value', '')
            $('#endDateMe').attr('data-value', '')
        })
    };

    ///输入框
    const _mainSearch = function () {
        SN.H5.WorkReportMain.ReceiveSearch.InputSearch();
    };

    //TODO : 初始化我收到的工作汇报
    const initData = () => {
        let _data = _vm.page;
        WorkReportMainApi.getWkrptsReceivedList(Object.assign({
            searchInfo: _vm.quickQuery,
            recipientId: SN.H5.WorkReportMain.Employee.id,
            reporterIds: receivePeopleList
        }, _data, _vm.pageScreening)).then(res => {
            let _page = {
                pageSize: 20,
                pageIndex: _data.pageIndex + 1,
                totalPages: res.totalPages,
            }
            _vm._data.page = Object.assign({}, _page);
            if (res.items.length == 0) {
                leftList = [];
                return $('#received-infinite').empty().append(_isNothing);
            } else if (_data.pageIndex == 0) {
                $('#received-infinite').empty();
                leftList = [];
            }
            leftList.push(...res.items);
            let result = leftList.reduce((c, v) => {
                c[v.reportEndDate] = c[v.reportEndDate] || [];
                c[v.reportEndDate].push(v);
                return c;
            }, {});
            let _list = [];
            Object.keys(result).forEach(key => {
                _list.push({
                    value: key,
                    entries: result[key]
                })
            });
            $('#received-infinite').empty().append(_reportTemplate({ list: _list, format: ReportEnumToString, dateForMat: (data) => moment(data, 'YYYY-MM-DD HH:mm:ss').format('HH:mm'), isEdit: false }));
            $('.report-contents-item-box:last').css('margin-bottom', '50px')

        })
        $('#received-infinite').on('click', '.report-item', function () {
            const id = $(this).attr("myId");
            // return
            let url = `lookreport/reportdetail.html?v=${new Date().getTime()}&id=` + id;//此处拼接内容
            window.location.href = url;
            Utils.SetRouterState("lookreport", JSON.stringify({
                state: $('#look-report-page-navbar .weui-bar__item--on').attr('href'),
                main: $('#main-tabbar .weui-bar__item--on').attr('id')
            }));
        });
    }

    const _reset = () => {
        $('#received-infinite').empty();
        _vm.page = Object.assign({}, _page);
        initData();
    }

    //TODO : 初始化我提交的工作汇报
    const initMeData = () => {
        let _data = _vm.mePage;
        WorkReportMainApi.getWkrptsSubmitedList(Object.assign({
            searchInfo: _vm.quickMeQuery,
            reporterId: SN.H5.WorkReportMain.Employee.id
        }, _data, _vm.mePageScreening)).then(res => {
            let _page = {
                pageSize: 20,
                pageIndex: _data.pageIndex + 1,
                totalPages: res.totalPages,
            }
            _vm._data.mePage = Object.assign({}, _page);
            if (res.items.length == 0) {
                rightList = [];
                return $('#me-received-infinite').empty().append(_isNothing);
            } else if (_data.pageIndex == 0) {
                $('#me-received-infinite').empty();
                rightList = [];
            }
            rightList.push(...res.items);
            let result = rightList.reduce((c, v) => {
                c[v.reportEndDate] = c[v.reportEndDate] || [];
                c[v.reportEndDate].push(v);
                return c;
            }, {});
            let _list = [];
            Object.keys(result).forEach(key => {
                _list.push({
                    value: key,
                    entries: result[key].sort(function (a, b) {
                        return Date.parse(b.createTime) - Date.parse(a.createTime);
                    })
                });
            })

            // console.log(_reportTemplate({list : _list}));
            $('#me-received-infinite').empty().append(_reportTemplate({ list: _list, format: ReportEnumToString, dateForMat: (data) => moment(data, 'YYYY-MM-DD HH:mm:ss').format('HH:mm'), isEdit: true }));
            $('.report-contents-item-box:last').css('margin-bottom', '50px')

        })
        $('#me-received-infinite').on('click', '.report-item', function () {
            const id = $(this).attr("myId");
            let url = `lookreport/reportdetail.html?v=${new Date().getTime()}&id=` + id;//此处拼接内容
            window.location.href = url;
            Utils.SetRouterState("lookreport", JSON.stringify({
                state: $('#look-report-page-navbar .weui-bar__item--on').attr('href'),
                main: $('#main-tabbar .weui-bar__item--on').attr('id')
            }));

        });
    }
    const _resetMe = () => {
        $('#me-received-infinite').empty();
        _vm.mePage = Object.assign({}, _page);
        initMeData();
    }

    /*********我提交的筛选*********** */
    //TODO :初始化模板选择
    const templatePickerInitMe = () => {

        $("#templatePicker").picker({
            toolbarCloseText: '确定',
            toolbarTemplate: _picker,
            title: "请选模板类型",
            cols: [
                {
                    textAlign: 'center',
                    values: ['所有类别', '日报', '周报', '月报', '汇报']
                }
            ],
            //确定选择时的操作
            onClose: function (data) {
                if (_vm.mePageScreening.reportType == _type[data.value]) return;
                _vm.mePageScreening.reportType = _type[data.value];
                $('#templatePicker-text').text(data.value);
                _resetMe()
            }
        });
        $('#templatePicker-text').on('click', function (e) {
            e.stopPropagation();
            $("#templatePicker").picker("open");
        });
    }
    //初始化时间选择
    const datetimePickerInitMe = () => {
        $('#datePicker-text').on('click', function (e) {
            e.stopPropagation();
            $("#datePicker").picker("open");
            //TODO : 我提交的时间选择器初始化赋值
            //Date :2022-02-15 16:58:06
            //create张双磊          
            $("#startDateRe").text(_vm.mePageScreening.reportStartDate || '开始时间')
            $("#endDateRe").text(_vm.mePageScreening.reportEndDate || '结束时间')
            $("#startDateRe").attr("data-value", _vm.mePageScreening.reportStartDate)
            $("#endDateRe").attr("data-value", _vm.mePageScreening.reportEndDate)
        });
        let index = 0;
        $("#datePicker").datetimePicker(
            {
                toolbarTemplate: toolbarTemplateMe,
                // max:formatDate,
                toolbarCloseText: "确定",
                yearSplit: '年',
                monthSplit: '月',
                dateSplit: '日',
                times: function () {
                    return [];
                },
                //选择值变化时的操作
                onChange: function (picker) {
                    if (index == 0) return index++;
                    let value = picker.value[0] + '-' + picker.value[1] + '-' + picker.value[2]
                    $('.dtPicker-hightLight-Cotainer .chooseDate').text(value);
                    let id = $('.dtPicker-hightLight-Cotainer .chooseDate').attr("id")
                    $(`#${id}`).attr("data-value", value);
                },
                //确定选择时的操作
                onClose: function (picker) {
                    let _start = $("#startDateRe").attr("data-value");
                    let _end = $("#endDateRe").attr("data-value");
                    console.log(_start, _end);
                    _vm.mePageScreening.reportStartDate = _start || '';
                    _vm.mePageScreening.reportEndDate = _end || '';
                    $('#datePicker-text').text(_dateTime(_start, _end));
                    _resetMe();
                    // 关闭日期时间选择器重新打开时重置默认选中值
                    // picker.value = Utils.GetNowFormatDate('-').split('-')
                }
            }
        );

    }
    const changeTime = () => {
        $(document).on('click', '.dtPicker-container a', function () {
            $(this).addClass('dtPicker-hightLight-Cotainer')
            $(this).removeClass('dtPicker-normal-Cotainer')
            $(this).siblings().removeClass('dtPicker-hightLight-Cotainer')
            $(this).siblings().addClass('dtPicker-normal-Cotainer')
        })
        // $('.dtPicker-container a').click(function () {
        //     $(this).addClass('dtPicker-hightLight-Cotainer')
        //     $(this).removeClass('dtPicker-normal-Cotainer')
        //     $(this).siblings().removeClass('dtPicker-hightLight-Cotainer')
        //     $(this).siblings().addClass('dtPicker-normal-Cotainer')
        // })
    }

    /******我收到的筛选****** */
    const templatePickerInit = () => {
        $("#me-search-type").picker({
            toolbarCloseText: '确定',
            toolbarTemplate: _picker,
            title: "请选模板类型",
            cols: [
                {
                    textAlign: 'center',
                    values: ['所有类别', '日报', '周报', '月报', '汇报']
                }
            ],
            //确定选择时的操作
            onClose: function (data) {
                if (_vm.pageScreening.reportType == _type[data.value]) return;
                _vm.pageScreening.reportType = _type[data.value];
                $('#me-search-type-text').text(data.value);
                _reset()
            }
        });
        $('#me-search-type-text').on('click', function (e) {
            e.stopPropagation();
            $("#me-search-type").picker("open");
        });
    }
    //初始化时间选择
    const datetimePickerInit = () => {
        $('#me-search-date-text').on('click', function (e) {
            e.stopPropagation();
            //TODO : 我收到的时间选择器初始化赋值
            //Date :2022-02-15 16:24:56
            //create张双磊
            $("#me-search-date").picker("open");
            $("#startDateMe").text(_vm.pageScreening.reportStartDate || '开始时间')
            $("#endDateMe").text(_vm.pageScreening.reportEndDate || '结束时间')
            $("#startDateMe").attr("data-value", _vm.pageScreening.reportStartDate)
            $("#endDateMe").attr("data-value", _vm.pageScreening.reportEndDate)
        });
        $('.sn-drop-down').on('click', function (e) {
            e.stopPropagation();
        });
        let index = 0;
        $("#me-search-date").datetimePicker(
            {
                toolbarTemplate: toolbarTemplate,
                // max:formatDate,
                toolbarCloseText: "确定",
                yearSplit: '年',
                monthSplit: '月',
                dateSplit: '日',
                times: function () {
                    return [];
                },
                //选择值变化时的操作
                onChange: function (picker) {
                    if (index == 0) return index++;
                    let value = picker.value[0] + '-' + picker.value[1] + '-' + picker.value[2]

                    $('#me-date-screening .dtPicker-hightLight-Cotainer .chooseDate').text(value);
                    let id = $('#me-date-screening .dtPicker-hightLight-Cotainer .chooseDate').attr("id")
                    $(`#${id}`).attr("data-value", value);
                },
                //确定选择时的操作
                onClose: function (picker) {
                    let _start = $("#startDateMe").attr("data-value");
                    let _end = $("#endDateMe").attr("data-value");
                    _vm.pageScreening.reportStartDate = _start || '';
                    _vm.pageScreening.reportEndDate = _end || '';
                    // 关闭日期时间选择器重新打开时重置默认选中值
                    // picker.value = Utils.GetNowFormatDate('-').split('-');
                    $('#me-search-date-text').text(_dateTime(_start, _end));
                    _reset();

                }
            }
        );

    }

    const _dateTime = (start, end) => {
        let _timeStr = "所有日期";
        if (Utils.IsNotNull(start) && Utils.IsNotNull(end)) {
            _timeStr = `${moment(start, 'YYYY-MM-DD').format('MM/DD')}-${moment(end, 'YYYY-MM-DD').format('MM/DD')}`
        }
        if (Utils.IsNotNull(start) && !Utils.IsNotNull(end)) _timeStr = start;
        if (!Utils.IsNotNull(start) && Utils.IsNotNull(end)) _timeStr = end;
        return _timeStr;
    }


})(window, document, jQuery)